<?php
namespace Home\Controller;

use Think\Controller;

class SettlementController extends Controller
{
  public function __construct()
  {
    parent::__construct();

    if (!is_cli_request()) {
      die('not allow');
    }
  }

  public function index()
  {
    error_reporting(E_ALL^E_NOTICE^E_WARNING);

    $start = strtotime('yesterday');
    $yesterday = date('Y-m-d 00:00:00', $start);
    $end = $start + 86400;
    $where = "o.payed_at >= {$start} AND o.payed_at < {$end} AND o.status in(2,4,5)";
    $result = M('orders')->alias('o')
             ->where($where)
             ->join("left join ".C('DB_PREFIX')."shops s on s.id = o.shop_id")
             ->field('sum(o.total_amount) as total_amount, s.id as shop_id, o.id as order_id')
             ->group('o.shop_id')
             ->select();

    $rate = 6;
    foreach ($result as $item) {
      if (!$item['shop_id']) {
        continue;
      }

      $today_start = date('Y-m-d H:i:s', strtotime('today'));
      $today_end   = date('Y-m-d H:i:s', strtotime('today') + 86400);
      $row_where = "shop_id = {$item['shop_id']} AND created_at >= '{$today_start}' AND created_at < '{$today_end}'";

      $row = M('settlements')->where($row_where)->find();
      if ($row) {
        continue;
      }

      $rate_amount = floor($item['total_amount'] * (1000 - $rate) / 1000 * 100) / 100;

      $data = array(
        'shop_id' => $item['shop_id'],
        'total_amount' => $item['total_amount'],
        'rate_amount' => $rate_amount,
        'rate' => $rate,
        'status' => 1,
        'day' => $yesterday,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s')
      );
      $settlement_id = M('settlements')->add($data);
      M('pay_logs')->where("order_id={$item['order_id']}")->save(array('settlement_id' => $settlement_id));
    }
  }
}
